Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

207
Views
How can create a function like findSum([1,2,3,5], 5) that second param is the sum of to element of array and return those two element in javascript?

I wanna write a function that receive two parameter that first one is an array and the second is an integer; So I wanna return two element of the array that their sum be equal the second function's parameter. For example in this case findSum([1,2,3,5], 5) my function will return 2 and 3 that their sum being 5. I wrote a function but I think it can be better with another optimized coding.

function findSum(arr, sum){
  for(element of arr) {
    const first_element = element;
    for(innerElement of arr){
      if((innerElement !== first_element) && (innerElement + element === sum) )
          return {first_element, innerElement}
    }
  }
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

So, one clear issue with your code is that findSum([2,2,3],4) won't work, because of this line: if((innerElement !== first_element). You should check indexes, rather than values to avoid this.

Very quick example:

findSum = (arr, sum) => {
        return arr.map((x, i) => {
            return arr.map((y, j) => {
                if(i === j) return null;
                return x + y === sum ? {x, y} : null;
            }).filter(x => x);
        }).flat()[0];
    }

Essentially, what I''m doing is very similar to your original version, with some slight tweaks.

Rather than using two for loops like you, I use two maps to iterate over the array. This gives me access to the index (i & j).

If i === j then it's the exact same element (and not just the same value) so we can ignore it. This solves the if((innerElement !== first_element) issue.

Then I check to see if the sum is correct and return the values, or null if it's incorrect. Filtering this array with filter(x => x) returns only the truthy elements, i.e. removes the nulls so we are left with all the matches.

We then flatten the array and return the first object as that's all we need, but we could change that to return all the matches. findSum([2,2,1,3], 4) has two matches for example.

Key concepts: Array.map Array.filter Array.flat

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!